package com.alibaba.citrus.cr.sales.plan.facade.service.statistics.stat.organization;

import com.alibaba.citrus.cr.common.annotation.FunctionInvoker;
import com.alibaba.citrus.cr.sales.plan.model.enums.ContractDataSourceEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.ContractStatDimensionEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.StatPoolTypeEnum;
import com.alibaba.citrus.cr.sales.plan.repository.request.StatOrganizationQueryRequest;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanStatScItemSDO;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.MonthContractAndRollingCountResponse;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QueryContractByCustomerDimensionRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.statistics.stat.SalesPlanStatAtomAbstract;
import com.alibaba.citrus.cr.sales.plan.facade.service.statistics.stat.model.SalesPlanStatRequest;
import com.alibaba.cz.base.tool.log.Log;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.PlanOrganizationStatCountRequest;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.PlanOrganizationStatCountResponse;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * @author luyi
 * @date 2021/12/2 11:20 下午
 */
public class OrganizationBusinessUnitStatService extends SalesPlanStatAtomAbstract {
    private static final Log log = Log.getLogger(OrganizationBusinessUnitStatService.class);

    public OrganizationBusinessUnitStatService(SalesPlanStatRequest statRequest, CountDownLatch latch){
        super.statRequest = statRequest;
        super.latch = latch;
    }

    @Override
    protected void handle(SalesPlanStatRequest statRequest) {
        statBusinessUnit(statRequest.getSalesPlan(),statRequest.getYear(),statRequest.getMonth());
    }

    @Override
    protected String taskName() {
        return "organizationBusinessUnitStat";
    }

    /**
     * 组织维度
     * 业务单元维度汇总
     *
     * @param salesPlan
     */
    @FunctionInvoker(printLog = true)
    private void statBusinessUnit(SalesPlanSDO salesPlan, String year, String month) {
        PlanOrganizationStatCountRequest request = new PlanOrganizationStatCountRequest();
        request.setPlanId(salesPlan.getId().toString());
        request.setPoolType(StatPoolTypeEnum.SC_ITEM.getPoolType());
        request.setBizType(SalesStatBizTypeEnum.BUSINESS_UNIT.getBizType());
        PlanOrganizationStatCountResponse response = planScItemService.planOrganizationStatCount(request);
        if (Objects.isNull(response)) {
            log.info("SalesPlanStatServiceImpl_scItemStat_statCount_is_null,statBusinessUnit");
            return;
        }
        Integer count = response.getCount();
        if (count == null || count <= 0) {
            log.info("SalesPlanStatServiceImpl_scItemStat_statCount_is_null,statBusinessUnit2");
            return;
        }
        int totalPage = (count + CUSTOMER_ADDRESS_PAGE_SIZE - 1) / CUSTOMER_ADDRESS_PAGE_SIZE;
        log.info("SalesPlanStatServiceImpl_statBusinessUnit_statCount_size={},totalPage={}",count,totalPage);
        for (int i = 1; i <= totalPage; i++) {
            StatOrganizationQueryRequest queryRequest = new StatOrganizationQueryRequest();
            queryRequest.setPlanId(salesPlan.getId().toString());
            queryRequest.setPoolType(StatPoolTypeEnum.SC_ITEM.getPoolType());
            queryRequest.setBizType(SalesStatBizTypeEnum.BUSINESS_UNIT.getBizType());
            queryRequest.setPage(i);
            queryRequest.setSize(CUSTOMER_ADDRESS_PAGE_SIZE);
            List<SalesPlanStatScItemSDO> salesPlanStatScItemList = salesPlanScItemStatRepository.statOrganization(queryRequest);
            if (CollectionUtils.isEmpty(salesPlanStatScItemList)) {
                log.info("SalesPlanStatServiceImpl_scItemStat_queryStatList_is_null,statBusinessUnit");
                return;
            }
            log.info("SalesPlanStatServiceImpl_statBusinessUnit_queryStatList_size={}",salesPlanStatScItemList.size());
            //批量查询销售组织合同量，合同金额
            Set<String> businessUnitList = salesPlanStatScItemList.stream().map(SalesPlanStatScItemSDO::getBizId).collect(Collectors.toSet());
            if (CollectionUtils.isEmpty(businessUnitList)) {
                log.info("SalesPlanStatServiceImpl_scItemStat_queryStatList_is_null,statBusinessUnit2");
                return;
            }

            Map<String, com.epoch.app.bcorder.model.dto.OrganizationSDO> bizOrgMap = salesPlanOutCommonService.getOrganizationMapByIds(businessUnitList,false);

            QueryContractByCustomerDimensionRequest queryContractRequest = new QueryContractByCustomerDimensionRequest();
            queryContractRequest.setType(ContractStatDimensionEnum.COMPANY.getCode());
            queryContractRequest.setContractYear(year);
            queryContractRequest.setPlanMonth(month);
            queryContractRequest.setOrgBusinessUnitCodes(Lists.newArrayList(businessUnitList));
            queryContractRequest.setDataSource(ContractDataSourceEnum.CUSTOMER.getCode());

            List<MonthContractAndRollingCountResponse> monthContractList = contractRepository.queryQuantityListByAddressAndScItem(queryContractRequest);
            Map<String, MonthContractAndRollingCountResponse> collect = Maps.newHashMap();
            if (CollectionUtils.isNotEmpty(monthContractList)) {
                collect = monthContractList.stream().collect(Collectors.toMap(MonthContractAndRollingCountResponse::getOrgBusinessUnitCode, m -> m));
            }
            for (SalesPlanStatScItemSDO planStatScItem : salesPlanStatScItemList) {
                planStatScItem.setPoolType(StatPoolTypeEnum.ORGANIZATION.getPoolType());
                planStatScItem.setBizType(SalesStatBizTypeEnum.BUSINESS_UNIT.getBizType());
                //需要查合同量补充
                MonthContractAndRollingCountResponse monthContract = collect.get(planStatScItem.getBizId());
                setStatContractInfo(planStatScItem, monthContract);
                calculateSatisfaction(salesPlan.getStatus(), planStatScItem);

                planStatScItem.setParentId(salesPlan.getOrgProvinceId());

                com.epoch.app.bcorder.model.dto.OrganizationSDO org = bizOrgMap.get(planStatScItem.getBizId());
                planStatScItem.setBizOutId(org.getCode());
            }
            Boolean result = salesPlanScItemStatRepository.batchCreatePlanScItem(salesPlanStatScItemList);
            log.info("SalesPlanStatServiceImpl_statcItem_batchCreatePlanScItem_result={},statBusinessUnit",result);
        }
    }
}
